package demo1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.Queue;

/**
 * Create by jsonor 2017/09/14
 * 连接池
 */
public class ConnectionPooled {

  // 存放一大顿的链接
  private Queue<Connection> pooled;
  // 存放的Connection的最大数量
  private static final int MAX_SIZE = 10;

  static {
    try {
      Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
      throw new ExceptionInInitializerError(e);
    }
  }

  /**
   * 构造函数，初始化连接池，生成10个链接存放在连接池中
   */
  public ConnectionPooled() {
    pooled = new LinkedList<>();

    for (int i = 0; i < MAX_SIZE; i++) {
      try {
        Connection cn = DriverManager.getConnection("jdbc:mysql:///test",
            "root", "123456789");
        pooled.add(cn);
      } catch (SQLException e) {
        throw new ExceptionInInitializerError(e);
      }
    }
  }

  /**
   * 获取一个链接
   * @return
   */
  public Connection getConnection() {
    return pooled.poll();
  }
}
